<template>
	<view class="row-around">
		<!-- 左侧操作栏 -->
		<view class="left">
			<Operation ref="operation" />
		</view>
		<!-- 右侧设备连接区 -->
		<view class="right">
			<view class="serialport_container">
				<!-- 如果设备已连接，显示电池状态 -->
				<view v-if="connectedDevice" class="battery-status">
					<battery-icon :quantity="quantity" style="margin-left: 25rpx;" />
				</view>
				<!-- 显示蓝牙和USB选择 -->
				<div v-show="!connectedDevice" class="options-container">
					<button @tap="selectBluetooth" :disabled="selectedOption == 'usb'" class="bluetooth-button">
						连接蓝牙
					</button>
					<button @tap="selectUSB" :disabled="selectedOption == 'bluetooth'" class="usb-button">
						连接USB
					</button>
				</div>
				<!-- 设备已连接后的按钮 -->
				<button v-show="connectedDevice" @click="expandButton" class="connection-button-container">
					{{ connectedDevice }}
				</button>
				<!-- 设备列表显示 -->
				<div v-show="isDeviceListVisible" class="device-list-container">
					<div class="device-list-header">
						<span>可用设备</span>
						<div class="header-buttons">
							<button @click="refreshDeviceList()" class="refresh-button">刷新设备</button>
							<button @click="goBack" class="back-button">返回</button>
						</div>
					</div>
					<scroll-view scroll-y="true" class="device-list">
						<div v-for="(item, index) in deviceList" :key="index" @click="bleConnect(item)"
							class="device-item">
							<text>设备: {{ item.name }} </text>
						</div>
					</scroll-view>
				</div>
			</view>

			<!-- 新增：鸽舍号显示模块 -->
			<view class="houseId row-center">
				{{geshe ? '鸽舍号：'+ geshe : '鸽舍号'}}
			</view>

			<!-- 功能页面 -->
			<read-nfc :key="refreshKey"  />
			<!-- Toast 与 Modal 组件 -->
			<u-toast ref="uToast" />
			<u-modal v-model="isModal" @confirm="disconnect" ref="uModal" :content="content"
				:show-cancel-button="true" />
		</view>
	</view>
</template>

<script>
	import bluetooth from '@/utils/ble.js'
	import batteryIcon from '@/components/batteryIcon.vue' //引入电池图标
	import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
	import Operation from '@/pages/operation/operation.vue'
	import ReadNfc from '@/pages/readNFC/readNFC.vue'
	import {
		mapGetters
	} from 'vuex'
	import {
		debounce
	} from '@/utils/debounce.js' //防抖方法
	import {
		format,
		formatSiteId
	} from '@/utils/format_HouseId.js'
	import {
		reqGetStatu,
		reqAddHouse, //新增卡号接口
		reqAbnormal,
		reqRecordOut,
		getExpection,
		reqExpection,
		deleteAbnormal
	} from '@/api/index.js'
	import mixin from '@/mixins/index.js'
	import operation from '../../store/modules/operation'
	// 引入串口读取插件
	const serialPort = uni.requireNativePlugin('dodo-uniplugin-usbSerialPort')
	export default {
		//为当前组件 “声明可用资源”，实现代码复用
		mixins: [mixin], 
		//声明可以使用的子组件
		components: {
			Operation, //左侧菜单
			ReadNfc, //右侧
			batteryIcon, //电池组件
		},
		//用于定义组件的 “响应式数据”，属于组件私有数据
		data() {
			return {
				nfcId: '',
				timer: null,
				debounceGetStatu: debounce(async () => {
					await this.getStatu();
					await this.getDate();
				}, 200),
				// path: '/dev/bus/usb/001/003'
				path: '',
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				// 判断连接成功与否
				connect: false,
				geshehao: '',
				show_hosueId: '',
				quantity: null, //电量
				isConnected: false, // 连接状态
				isDeviceListVisible: false, // 是否显示设备列表
				deviceList: [], // =蓝牙设备列表
				connectedDevice: '', // 记录已连接的设备
				selectedOption: '', // 记录选择的选项
				tabIndex: 0,
				curDevice: {
					name: '',
					deviceId: '',
					serviceId: '',
					characteristicId: ''
				},
				content: '',
				isModal: false, //控制是否断开连接弹窗
				refreshKey: 0, // 用于组件刷新的key，初始值0 
				geshe: '',
			}
		},
		
		//页面初次加载时的初始化操作
		async onLoad() {
			// 检查版本 只在app中有效 h5会报错
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
				console.log("A版本号", wgtinfo); //应用版本号
				appversion = wgtinfo.version
			})
			// #endif
			checkUpdate()
			
			//将初始业务操作类型设为 “查蛋”，修改state.operation
			this.$store.commit('SETOPERATION', 'CagenumberLay');
			
			this.onBLECharacteristicValueChange({
				  // value: new TextEncoder('utf-8').encode('000fff315c752e').buffer, // 一行生成 ArrayBuffer
				  value: new TextEncoder('utf-8').encode('000fff111eaf2e').buffer,
				  characteristicId: 'mock-char-id', // 其他字段随便填（函数内用不到）
				  deviceId: 'mock-device-id'
			});
		},
		
		//页面销毁时（1. 断开蓝牙连接；2. 关闭 USB 串口连接）
		onUnload() {
			bluetooth.disconnectBluetooth(this.curDevice.deviceId);
			this.Close();
		},
		
		//映射 Vuex 的 getters（全局计算属性）到当前组件的 computed（组件本地计算属性）中
		computed: {
			...mapGetters(['operation', 'changeNfcId', 'operationSiteId', 'show_nfcId', 'abnormal', 'layTime'])
		},
		
		//监听组件内响应式数据 nfcId 的变化
		watch: {
			nfcId(newValue, oldValue) {
				//nfcid变化，触发查蛋操作和获取相关比例操作
				if (newValue !== oldValue) {
					this.handleAfterNfcChange();
				}
			}
		},
		
		//下拉页面刷新时
		onPullDownRefresh() {
			console.log('onPullDownRefresh');
			this.deviceList = [];
			bluetooth.getBluetoothState().then(() => {
				bluetooth.startDiscoveryBluetooth().then(() => {
					uni.stopPullDownRefresh();
				})
			})
		},
		methods: {
			//监听后的回调函数
			async handleAfterNfcChange() {
			  // 1. 等待防抖后的getStatu和getDate执行完毕
			  await this.debounceGetStatu();
			  // 2. 等待getPR内部的dispatch执行完毕
			  await this.getPR();
			  // 3. 刷新组件：修改key值，触发组件重新渲染
			  this.refreshKey++; 
			  // 新增：强制更新组件内数据渲染
			  this.$nextTick(() => {
			    this.$forceUpdate();
			  });
			},
			//获取鸽仓相关比例数据（如抽蛋留窝比例）。
			getPR() {
				console.log('index.vue 中的 operationSiteId：', this.operationSiteId);
				if (this.operationSiteId) {
					const obj = {
						site_id: uni.getStorageSync('siteId')
					}
					this.$store.dispatch('getEWPR', obj)
				}
			},
			// 获取查蛋页面中的时间
			async getDate() {
				const obj = {
					siteId: uni.getStorageSync('siteId'),
					houseId: this.nfcId,
					twoOrSix: 3
				}
				console.log('茶蛋茶蛋');
				await this.$store.dispatch('getDate', obj);
			},
			//获取鸽仓 / 蛋的状态数据（核心业务接口请求）。
			getStatu() {
			  this.loading = true
			  const obj = {
				siteId: uni.getStorageSync('siteId'),
				houseId: this.nfcId
			  }
			  if (this.operation !== 'HouseChange' && this.operation !== 'HouseAdd') {
				reqGetStatu(obj).then(data => {
				  if (data.code === 200) {
					this.$store.commit('GETSTATU', data.statu);
					
					// 直接用后端返回的siteId、rowId、houseId拼接格式
					const houseId = `${data.siteId}-${data.rowId}-${data.houseId2}`;
					
					this.geshe = houseId;
					
					// 以下逻辑保留（处理opesiteid等）
					let opesiteid;
					try {
					  const siteIdStr = localStorage.getItem('siteId');
					  if (!siteIdStr) {
						opesiteid = 0;
					  } else {
						const parsed = JSON.parse(siteIdStr);
						opesiteid = parsed === 0 ? 0 : parsed.data;
					  }
					} catch (err) {
					  console.warn('siteId 解析失败，使用原始值：', err);
					  opesiteid = localStorage.getItem('siteId') || 0;
					}
					this.$store.commit('SETOPESITEID', opesiteid) //改的是operationSiteId状态
					this.$store.commit('SHOWNFC', houseId); // 存储拼接后的结果,显示鸽舍号
					this.$store.commit('SETLOADING', false)			
				  }
				}).catch((err) => {
				  uni.showToast({
					title: err.msg || '扫描成功',
					icon: 'none',
					duration: 1500
				  })
				  this.$store.commit('GETSTATU', [])
				}).finally(() => {
				  this.loading = false;
				  uni.stopPullDownRefresh();
				})
			  }
			},
			//批量触发核心数据请求，同步业务数据。
			dispatch() {
				this.$store.dispatch('getDate', {
					siteId: uni.getStorageSync('siteId'),
					houseId: this.nfcId,
					twoOrSix: 3
				})
				this.$store.dispatch('getStatu', {
					siteId: uni.getStorageSync('siteId'),
					houseId: this.nfcId
				})
				this.$store.dispatch('getEWPR', {
					site_id: uni.getStorageSync('siteId')
				})
			},
			// 断开所有连接
			disconnect() {
				this.quantity = '0' //电量置空
				// 断开蓝牙连接
				if (this.curDevice.deviceId) {
					bluetooth.disconnectBluetooth(this.curDevice.deviceId); // 确保设备 ID 存在再断开
				}
				// 断开 USB 连接（假设 this.Close() 是断开 USB 连接的函数）
				this.Close();
				// 重置 curDevice 对象，正确方式为修改其属性值
				this.curDevice = {
					name: '',
					deviceId: '',
					serviceId: '',
					characteristicId: ''
				};
				this.connectedDevice = '' //断开连接把单一的按钮清空
				this.selectedOption = null; // 记录当前选择
			},
			// 点击展开按钮
			expandButton() {
				this.content = '确定断开连接？'
				this.isModal = true
			},
			// 选择USB设备
			selectUSB() {
				bluetooth.disconnectBluetooth(this.curDevice.deviceId); //断开蓝牙连接
				this.initUsbSerialPort();
			},
			// 返回上一步
			goBack() {
				//断开蓝牙搜索
				bluetooth.stopDiscoveryBluetooth();
				// this.disconnect();
				this.isDeviceListVisible = false; // 隐藏设备列表
				this.selectedOption = null; // 重置选择状态
			},
			// 自动刷新设备列表
			refreshDeviceList() {
				this.selectBluetooth();
			},
			// 蓝牙 ============================
			bleConnect(bleDev) {
				bluetooth.connectBluetooth(bleDev.deviceId).then((deviceId) => {
					this.curDevice.name = bleDev.name;
					this.curDevice.deviceId = deviceId;
					console.log(deviceId)
					bluetooth.getServiceId(this.curDevice.deviceId).then((serviceId) => {
						this.curDevice.serviceId = serviceId;
						console.log(this.curDevice.deviceId, this.curDevice.serviceId)
						bluetooth.getCharacteId(this.curDevice.deviceId, this.curDevice.serviceId).then((
							characteristics) => {
							console.log(characteristics);
							let characteristicId = ''
							characteristics.forEach(item => {
								// 003 如果有可读和监听这两个为true 就监听这个特征
								if (item.properties.notify === true && item.properties
									.read === true) {
									// 监听
									characteristicId = item.uuid;
								}
							});
							this.curDevice.characteristicId = characteristicId;
							let index = this.deviceList.indexOf(bleDev); // 找到要删除的元素的索引
							if (index !== -1) {
								this.deviceList.splice(index, 1); // 删除该元素  
							}
							bluetooth.stopDiscoveryBluetooth();
							this.tabIndex = 1;
							console.log(this.curDevice.characteristicId)
							if (characteristicId) {
								bluetooth.startNotice(this.curDevice.deviceId, this.curDevice
									.serviceId, this.curDevice.characteristicId, this
									.onBLECharacteristicValueChange);
							}
						})
					})
				})
				this.connectedDevice = bleDev.name; // 记录已连接设备名称
				this.isConnected = true; // 标记为已连接
				this.isDeviceListVisible = false; // 隐藏设备列表
			},
			//监听蓝牙设备发送的数据，解析并触发对应业务逻辑。
			onBLECharacteristicValueChange(result) {
			    if (result.value) {
			        //原始数据就算是对方发字符串过来 监听的时候也会是ArrayBuffer 所以要转成字符串
			        let restr = bluetooth.ab2str(result.value).toLowerCase() //转为小写和usb保持一致
			        console.log('接受的数据为: ' + restr)
			        if (restr.substring(0, 14) === 'batterypercent') {
			            this.quantity = Math.floor(restr.substring(15, restr.length));
			        }
			        // 在这里对监听到的数据进行处理
			        if (restr.substring(0, 6) === '000fff' && this.operation !== 'HouseChange' && this
			            .operation !== 'HouseAdd') {
			            this.nfcId = restr.substring(6, restr.length); //修改this.nfcid 触发watch
			            this.$store.commit('SETNFC', restr.substring(6, restr.length)); //将局部nfcid 6-末位 即真正nfcid存入store
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			            // this.$store.commit('SETOPERATION', 'CagenumberLay');
			        } else if (restr.substring(0, 6) === 'fff000' && this.operation ===
			            'CagenumberLay') {
			            const cageId = Number(restr.substring(6, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                //发送抽蛋请求
			                this.whipEggs(cageId).then(data => {
			                    if (data.code === 200) {
			                        this.dispatch()
			                        //  请求成功触发抽蛋音频
			                        this.whip()
			                    }
			                    this.$refs.uToast.show({
			                        title: data.msg,
			                        type: data.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (restr.substring(0, 6) === 'ffff00' && this.operation === 'CagenumberLay') {
			            const cageId = Number(restr.substring(restr.length - 1, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.liuwo(cageId).then(data => {
			                    if (data.code === 200) {
			                        this.dispatch()
			                        //留窝
			                        this.stay()
			                    }
			                    this.$refs.uToast.show({
			                        title: data.msg,
			                        type: data.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (restr.substring(0, 6) === 'fffff0' && this.operation === 'CagenumberLay') {
			            const cageId = Number(restr.substring(restr.length - 1, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.fallback(cageId).then(resp => {
			                    if (resp.code === 200) {
			                        this.dispatch();
			                        //撤回
			                        this.withdraw()
			                    }
			                    this.$refs.uToast.show({
			                        title: resp.msg,
			                        type: resp.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (restr.substring(0, 6) === '000fff' && this.operation ==
			            'HouseChange') { //当页面在更改仓号且读卡时
			            // const changenfcid = restr.substring(6, restr.length);
			            this.$store.commit('SETCHANGENFC', restr.substring(6, restr.length));
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			        } else if (restr.substring(0, 6) === '000fff' && this.operation == 'HouseAdd') { //当页面在添加卡号且读卡时
			            this.$store.commit('SETADDNFC', restr.substring(6, restr.length));
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			        } else if (restr.substring(0, 6) === 'fff000' && this.operation == 'Expection') {
			            //这里是杆子处理异常记录的方法
			            const cageId = Number(restr.substring(6, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                // 抛出事件总线 让cagenumber页面调用自己的方法 传过去abnormal 判断是那个异常页面调用方法
			                this.$cage.$emit('sednAbnormal', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        } else if (restr.substring(0, 6) === 'ffff00' && this.operation == 'Expection') {
			            const cageId = Number(restr.substring(restr.length - 1, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.$cage.$emit('abnormalsettle', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        } else if (restr.substring(0, 6) === 'fffff0' && this.operation == 'Expection') {
			            const cageId = Number(restr.substring(restr.length - 1, restr.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.$cage.$emit('withdraw', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        }
			    }
			},
			//筛选并更新蓝牙设备列表，避免重复设备。
			onDevDiscovery(devList) {
				devList.forEach((item) => {
					if (item.name.substring(0, 4) == 'Card') {
						let isHave = this.deviceList.some((dev, idx) => {
							if (dev.name === item.name) {
								// 更新已存在的项（如果需要的话）  
								this.deviceList[idx] = item;
								return true; //找到了就退出 some 的循环  
							}
							return false;
						});
						if (!isHave) {
							// 如果没有找到，就添加到 deviceList 中  
							this.deviceList.push(item);
						}
					}
				});
			},
			// 选择蓝牙设备
			async selectBluetooth() {
				this.Close(); // 断开usb连接
				this.selectedOption = 'bluetooth'; // 记录当前选择
				bluetooth.stopDiscoveryBluetooth();
				this.deviceList = [];
				bluetooth.getBluetoothState().then(() => {
					bluetooth.startDiscoveryBluetooth().then(() => {
						bluetooth.onBluetoothDeviceFound(this.onDevDiscovery);
					});
				});
				uni.onBLEConnectionStateChange((res) => {
					// 监听蓝牙连接状态变化
					if (!res.connected) {
						console.log(`Device ${ res.deviceId} disconnected`);
						// 执行断开连接后的操作，例如更新UI或重新连接
						this.isModal = true;
						this.content = '蓝牙已断开！';
					} else {
						console.log(`Device ${res.connected} connected`);
						this.$refs.uToast.show({
							title: '蓝牙连接成功',
							type: 'success',
							duration: '800',
							position: 'top'
						})
					}
				});
				this.isDeviceListVisible = true; // 显示设备列表
			},
			// 串口 ========================
			// 初始化
			initUsbSerialPort() {
				this.connect = false;
				serialPort.initSerialPort("usb", (res) => {
					if (res?.list.length) {
						console.log(res.list)
						if (this.path === res.list[0] && this.connect === true) {
							uni.showToast({
								title: '设备已连接',
								icon: 'none'
							})
							uni.stopPullDownRefresh()
						} else {
							this.path = res.list[0]
							this.Open()
						}
					} else {
						uni.showToast({
							title: '未插入设备',
							icon: 'none'
						})
						this.connect = false
						uni.stopPullDownRefresh()
					}
				})
			},
			// 关闭所有 USB 串口连接。
			Close() {
				serialPort.serialPortCloseAll(res => {
					this.open = false
				})
			},
			//打开指定路径的 USB 串口，准备参数配置。
			Open() {
				uni.showLoading({
					title: '正在连接NFC外接读取...',
					icon: 'none'
				})
				uni.stopPullDownRefresh()
				// let path = '/dev/bus/usb/001/003'
				let path = this.path
				serialPort.openSerialPort(path, res => {
					if (res.success) {
						setTimeout(() => {
							this.setSerialPort() //在打开串口后需要设置串口参数
						}, 1000)
					}
				})
			},
			// 设置串口
			setSerialPort() {
				let params = {
					// path: '/dev/bus/usb/001/002',
					path: this.path,
					baudRate: '9600', // 波特率 
					parity: '0', // 校验位:：0(不校验)、1(奇校验)、2(偶校验)
					dataBits: '8', //  数据位:5，6，7，8
					stopBits: '1', // 停止位:1、2
					flowCon: '0', // 流控:0(不使用流控)、1(使用流控)
				}
				serialPort.setSerialPort(...Object.values(params), (res) => {
					if (res.success) {
						setTimeout(() => {
							this.onListenerHex() //设置串口成功后即可开始监听串口数据
							uni.showToast({
								title: '连接成功!',
								icon: 'success'
							})
							this.isConnected = true; // 标记为已连接 控制按钮
							this.connect = true
							this.connectedDevice = 'USB连接中'; // 记录已连接设备名称
						}, 500)
					}
				})
			},
			//监听 USB 串口接收的数据，解析逻辑与蓝牙数据一致。
			onListenerHex() {
			    uni.hideLoading()
			    // let path = '/dev/bus/usb/001/002'
			    let path = this.path
			    // 以十六进制返回 onSerialPortDataListenerHex
			    // 以字符串返回 onSerialPortDataListenerASCII
			    // 以字节返回 onSerialPortDataListenerByte
			    serialPort.onSerialPortDataListenerASCII(path, receive => {
			        //监听接收数据 
			        const nfcId = receive.toLowerCase();
			        // if (nfcId.substring(0, 14) === 'batterypercent') {
			        // 	this.quantity = Math.floor(nfcId.substring(15, nfcId.length));
			        // }
			        if (nfcId.substring(0, 6) === '000fff' && this.operation !== 'HouseChange' &&
			            this
			            .operation !== 'HouseAdd') {
			            this.nfcId = nfcId.substring(6, nfcId.length); //修改this.nfcid 触发watch
			            this.$store.commit('SETNFC', nfcId.substring(6, nfcId
			                .length)); //将局部nfcid 6-末位 即真正nfcid存入store
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			            // this.$store.commit('SETOPERATION', 'CagenumberLay');
			        } else if (nfcId.substring(0, 6) === 'fff000' && this.operation ===
			            'CagenumberLay') { //operation页面在查蛋页面
			            // this.$refs.operation.$refs.operation.layEggs(Number(nfcId.substring(6,nfcId.length)))
			            const cageId = Number(nfcId.substring(6, nfcId.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                //发送抽蛋请求
			                this.whipEggs(cageId).then(data => {
			                    if (data.code === 200) {
			                        this.dispatch()
			                        //  请求成功触发抽蛋音频
			                        this.whip()
			                    }
			                    this.$refs.uToast.show({
			                        title: data.msg,
			                        type: data.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (nfcId.substring(0, 6) === 'ffff00' && this.operation ===
			            'CagenumberLay') {
			            const cageId = Number(nfcId.substring(nfcId.length - 1, nfcId.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.liuwo(cageId).then(data => {
			                    if (data.code === 200) {
			                        this.dispatch()
			                        //留窝
			                        this.stay()
			                    }
			                    this.$refs.uToast.show({
			                        title: data.msg,
			                        type: data.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (nfcId.substring(0, 6) === 'fffff0' && this.operation ===
			            'CagenumberLay') {
			            const cageId = Number(nfcId.substring(nfcId.length - 1, nfcId.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.fallback(cageId).then(resp => {
			                    if (resp.code === 200) {
			                        this.dispatch();
			                        //撤回
			                        this.withdraw()
			                    }
			                    this.$refs.uToast.show({
			                        title: resp.msg,
			                        type: resp.type,
			                        duration: '800',
			                        position: 'top'
			                    })
			                })
			            }
			        } else if (nfcId.substring(0, 6) === '000fff' && this.operation ==
			            'HouseChange') { //当页面在更改仓号且读卡时
			            // const changenfcid = nfcId.substring(6, nfcId.length);
			            this.$store.commit('SETCHANGENFC', nfcId.substring(6, nfcId.length));
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			        } else if (nfcId.substring(0, 6) === '000fff' && this.operation ==
			            'HouseAdd') { //当页面在添加卡号且读卡时
			            this.$store.commit('SETADDNFC', nfcId.substring(6, nfcId.length));
			            this.show = false;
			            this.$store.commit('SETOPEN', true);
			        } else if (nfcId.substring(0, 6) === 'fff000' && this.operation ==
			            'Expection') {
			            //这里是杆子处理异常记录的方法
			            const cageId = Number(nfcId.substring(6, nfcId.length))
			            // this.$refs.uToast.show({
			            // 	title: '这里进入了单击监听' + cageId,
			            // 	duration: '1000',
			            // 	position: 'top'
			            // })
			            if (cageId <= 8) {  // 修改为 <= 8
			                // 抛出事件总线 让cagenumber页面调用自己的方法 传过去abnormal 判断是那个异常页面调用方法
			                this.$cage.$emit('sednAbnormal', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        } else if (nfcId.substring(0, 6) === 'ffff00' && this.operation ==
			            'Expection') {
			            const cageId = Number(nfcId.substring(nfcId.length - 1, nfcId.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.$cage.$emit('abnormalsettle', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        } else if (nfcId.substring(0, 6) === 'fffff0' && this.operation ==
			            'Expection') {
			            const cageId = Number(nfcId.substring(nfcId.length - 1, nfcId.length))
			            if (cageId <= 8) {  // 修改为 <= 8
			                this.$cage.$emit('withdraw', {
			                    abnormal: this.abnormal,
			                    cageId: cageId
			                });
			            }
			        }
			    })
			},
			//获取所有可用 USB 串口设备路径，生成带默认参数的设备列表。
			getAllDeicesPath() {
				serialPort.getAllDeicesPath((res) => {
					this.res = res
					if (res?.list) {
						reactiveData.serialportList = res.list.map((iMap) => {
							let item = {}
							item.path = iMap
							item.baudRate = '9600' // 波特率
							item.parity = '0' // 校验位:：0(不校验)、1(奇校验)、2(偶校验)
							item.dataBits = '8' //  数据位:5，6，7，8
							item.stopBits = '1' // 停止位:1、2
							item.flowCon =
								'0' // 流控:0(不使用流控)、1(硬件流控RTS/CTS)、2(软件流控XON/XOFF)
							item.sendStr = '87654321'
							item.open = false //串口打开状态
							return item
						})
					}
				})
			},
			// // 查看串口状态
			serialPortStatus(path) {
				serialPort.serialPortState(path, (res) => {
					if (res?.success) {
						this.path = path
						uni.showToast({
							icon: 'none',
							title: `串口[${path}]已打开`,
							duration: 2000
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: `串口[${path}]未打开`,
							duration: 2000
						});
					}
				})
			},
			//创建音频实例，处理音频播放生命周期。
			createAudio(audioSrc) {
				this.innerAudioContext = uni.createInnerAudioContext(); //创建播放器对象
				this.innerAudioContext.src = audioSrc; //生成的mp3音频文件地址
				this.innerAudioContext.play(); //执行播放
				this.innerAudioContext.onEnded(() => {
					console.log(this.innerAudioContext);
					//播放结束
					this.innerAudioContext.destroy();
					this.innerAudioContext = null;
				});
				this.innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				})
			},
			//抽蛋音频播报
			whip() {
				this.createAudio('../../static/audio/whip.mp3');
			},
			//留窝音频播报
			stay() {
				this.createAudio('../../static/audio/stay.mp3');
			},
			// 撤回音频播报
			withdraw() {
				this.createAudio('../.././static/audio/withdraw.mp3');
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}
	
	.row-around{
		height: 100vh;
		display: flex;
		align-items: flex-start;
	}

	.left {
		width: 30%;
		height: 100vh;
		overflow-y: auto;
		border-right: 1px solid #E8F2FC;
	}

	.right {
		width: 70%;
		height: 100vh;
		overflow-y: auto;
		padding: 5rpx;
		box-sizing: border-box; /* 新增：确保padding不撑大宽度 */
	}
	.serialport_container {
		width: 100%;
		height: 5vh;
		position: relative;
	}
	.options-container {
		position: absolute;
		right: 3%;
		display: flex;
		gap: 10rpx;
		height: 100%;
	}

	.bluetooth-button,
	.usb-button {
		display: flex;
		align-items: center;
		padding: 0px 10px;
		font-size: 16px;
		color: white;
		border-radius: 10px;
		border: none;
		cursor: pointer;
		white-space: nowrap;
		/* 禁止换行 */
		width: auto;
		/* 宽度自动扩展 */
		flex-shrink: 0;
		/* 防止在父容器中被压缩 */
	}

	.bluetooth-button {
		background-color: #007bff;
		/* 蓝色 */
	}

	.usb-button {
		background-color: #28a745;
		/* 绿色 */
	}

	.bluetooth-button:disabled,
	.usb-button:disabled {
		background-color: #ccc;
		/* 灰色 */
		cursor: not-allowed;
	}

	.device-list-container {
		position: absolute;
		top: 5vw;
		right: 5%;
		justify-content: space-around;
		width: 50%;
		background-color: #f9f9f9;
		margin-top: 20px;
		width: 250px;
		display: flex;
		flex-direction: column;
		z-index: 10086;
		border-radius: 0.4cm;
	}

	.device-list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}

	.header-buttons {
		display: flex;
	}

	.back-button,
	.refresh-button {
		background-color: #ffc107;
		border: none;
		border-radius: 5px;
		padding: 5px 10px;
		color: white;
		cursor: pointer;
		margin-left: 10px;
		margin-top: 10px;
	}

	.device-list {
		height: 150px;
		width: 100%;
	}

	.device-item {
		padding: 10px;
		border: 1px solid #ddd;
		cursor: pointer;
		background-color: #fff;
		border-radius: 0.4cm;
	}

	.device-item:hover {
		background-color: #e6f7ff;
	}

	/* 新增：鸽舍号样式 */
	.houseId {
	    width: 100%;
	    margin: 40rpx auto 10rpx; /* 增加上边距 */
	    padding: 18.12rpx 18.12rpx;
	    font-size: 39.86rpx;
	    color: #fff;
	    background-color: #7d9ad2;
	    border-radius: 8rpx;
	    box-sizing: border-box;
	}

	/* 新增：居中布局类 */
	.row-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.connection-button-container {
	    position: absolute;
	    right: 3%;
	    top: 0; /* 明确指定顶部位置 */
	    display: flex;
	    align-items: center;
	    padding: 0 10px;
	    height: 100%; /* 与容器高度一致 */
	    background-color: #2ecc71; /* 默认背景色 */
	    color: white;
	    border: none;
	    border-radius: 10px;
	    cursor: pointer;
	    white-space: nowrap;
	    z-index: 1; /* 确保层级适当 */
	}
</style>